'''
Author: duliang thinktanker@163.com
Date: 2024-04-19 16:14:45
LastEditors: duliang thinktanker@163.com
LastEditTime: 2024-07-02 20:15:29
FilePath: \control-net\ztemp.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from sklearn.linear_model import LinearRegression
import numpy as np
import time
import matplotlib.pyplot as plt
import sqlite3

# from getgkdb import get_prediction


def get_prediction(time_list, data_list, plus_time, debug=False):
    result = []
    res = 0
    data = np.array(time_list).reshape(-1, 1)
    for i in range(0, len(data_list)):
        print(data_list[i])
        labels = np.array(data_list[i])
        # 使用线性回归模型
        model = LinearRegression()
        model.fit(data, labels)
        next_time = int(time.time()) + plus_time
        # 预测未来的值
        future_data = np.array([next_time]).reshape(-1, 1)  # 预测时间为next_time时的值
        prediction = model.predict(future_data)
        delta = prediction[0] - labels[0]
        if labels[0]:
            rate = delta / labels[0] * 100
        else:
            rate = 0
        if debug:
            print("预测值:", prediction[0])
            print("当前值:", labels[0])
            print('rate:', rate)
            print('delta:', delta)
        if rate:
            if abs(rate) > 1:
                if rate > 0:
                    # print("上涨")
                    res = 1
                else:
                    # print("下跌")
                    res = 2
            else:
                res = 0
        else:
            res = 3
            # 可视化
        pre_value = model.predict(data)
        start_value = pre_value.tolist()[0]
        end_value = pre_value.tolist()[-1]
        if debug:
            plt.scatter(data, labels, color='black')
            plt.plot(data, pre_value, color='blue', linewidth=3)
            plt.show()
        result.append(f'{res}@{round(prediction[0],2)}')
    return result, [start_value, end_value]


if __name__ == '__main__':
    db1_path = './data/hisdata.db'
    result = []
    conn = sqlite3.connect(db1_path)
    c = conn.cursor()
    sqltxt = "SELECT time FROM swll ORDER BY time DESC LIMIT 2"
    rs = c.execute(sqltxt)
    rf = rs.fetchone()
    now_time = rf[0]
    # result.append(
    #     time.strftime(r"%y年%m月%d日%H时%M分%S秒", time.localtime(now_time)) + "\n")
    start_time = now_time - 8 * 60 * 60
    # sqltxt = f"SELECT sysw,xysw,sqsw,time FROM swll WHERE TIME BETWEEN {start_time} AND {now_time} ORDER BY time DESC"
    # sqltxt = sqltxt = f"SELECT mgyl,time FROM gongshui WHERE TIME BETWEEN {start_time} AND {now_time} ORDER BY time DESC"
    sqltxt = f"""SELECT Uab,Ubc,Uca,Ia,Ib,Ic,P,Q,cos,lcU,lcI,time FROM dianyadianliu WHERE ename="{1}" AND TIME BETWEEN {start_time} AND {now_time} ORDER BY time DESC"""

    rs = c.execute(sqltxt)
    rf = rs.fetchone()
    print(rf)
    # 最新一组
    # cur_data = list(rf[0])
    # if rf:
    #     # res_list = []
    #     for i in range(0, len(rf[0])):
    #         try:
    #             flat_numbers = [num[i] for num in rf[2:]]
    #             result.append(flat_numbers)
    #         except Exception as e:
    #             print(e)
    #             # flat_numbers = [
    # conn.close()
    # plus_time = 60 * 30
    # time_list = result[-1]
    # # get_prediction(time_list, result, plus_time, debug=False)

    # get_prediction(time_list, result[:-1], plus_time, debug=True)

    # # print('当前数据：', label_data)
    # # print('预测数据：', prediction_data)
    # # print('真实数据：', cur_data[:-1])

    # # result2 = [
    # #     f'{round(abs((a - b) / a) * 100, 2)}%'
    # #     for a, b in zip(cur_data, prediction_data)
    # # ]
    # # print(result2)
